package top.easycode.app.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;



/**
 * 对分页的基本数据进行一个简单的封装
 */
public class Page<T>  {

    private int pageNo = 1;//页码，默认是第一页
    private int pageSize = 15;//每页显示的记录数，默认是15
    private int totalRecord;//总记录数
    private int totalPage;//总页数
    private List<T> results;//对应的当前页记录
    private T t;//传入需要查找的对象

    public Page(T t, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            pageNo = 1;
            pageSize = 10;
        }
        this.t = t;
        this.pageSize = pageSize;
        this.pageNo = pageNo;
    }

    public Page() {
        // TODO Auto-generated constructor stub
    }

    private Map<String, Object> params = new HashMap<String, Object>();//其他的参数我们把它分装成一个Map对象

    public T getT() {

        return t;
    }

    public void setT(T t) {
        this.params = objectToMap(t);
        this.t = t;
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
        //在设置总页数的时候计算出对应的总页数，在下面的三目运算中加法拥有更高的优先级，所以最后可以不加括号。
        int totalPage = totalRecord % pageSize == 0 ? totalRecord / pageSize : totalRecord / pageSize + 1;
        this.setTotalPage(totalPage);
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getResults() {
        return results;
    }

    public void setResults(List<T> results) {
        this.results = results;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    @SuppressWarnings({"rawtypes"})
    public static Map objectToMap(Object parameter) {
        if (null == parameter)
            return new HashMap();
        if (parameter instanceof Map) {
            return (Map) parameter;
        } else {
            try {
                return PropertyUtils.describe(parameter);
            } catch (Exception e) {
//				ReflectionUtils.handleReflectionException(e);
                new RuntimeException("从对象转换成map异常", e);
                return null;
            }
        }
    }

}